<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Expresssend{
    public $WALLTECH_SERVER = 'http://qa.etowertech.com';
    public $SECRET_KEY = '79db9e5OEeOpvgAVXUFWSD';
    public $ACCESS_TOKEN = 'test5AdbzO5OEeOpvgAVXUFE0A';
    public function __construct()
    {
        $this->CI =& get_instance();
        $this->CI->load->model('Function_m','fun');
        $this->CI->load->library('Tpl');
        $this->db = $this->CI->load->database('default', TRUE);
        $this->config=$this->CI->load->database('default', TRUE);
        if($this->CI->config->item("shipment_conf_ubi")){
                $user_conf_json = stripslashes($this->CI->config->item("shipment_conf_ubi"));
                $user_conf = unserialize($user_conf_json);
               $this->WALLTECH_SERVER=$user_conf['api_url'];
               $this->SECRET_KEY=$user_conf['user_id'];//
               $this->ACCESS_TOKEN=$user_conf['pass']; 
        }
    }
     function shipment($order_ids){
        $express_results=array();
        $success=0;
		$user_conf_json = stripslashes($this->CI->config->item("shipment_conf_dhl"));
		$user_conf = unserialize($user_conf_json);

        foreach($order_ids as $key=>$order_data){
            $rsdb = $this->db->get_one("SELECT order_id,email FROM db_order_list WHERE order_sn='".$order_data['orderID']."'");
            
            //test account:  prasanta    prasanta    SHFUMANNET   vS18rdyaFG
			$order_data["customerid"] = addslashes($order_data["customerid"]);
            $order_data["customerid"]=str_replace("&","",$order_data["customerid"]);
            echo '开始处理'.$order_data['orderID'].'的交运..<br />';
            $order_data["customeraddress"]=str_replace("’","'",$order_data["customeraddress"]);
            $order_data["customeraddress"]=str_replace("&","",$order_data["customeraddress"]);
            
			$address1 = substr($order_data["customeraddress"],0,35);
			$address2 = substr($order_data["customeraddress"],35,35);
			$address3 = substr($order_data["customeraddress"],70,35);
            if($order_data["customertel1"]=='' || $order_data["customertel1"]=='null' || $order_data["customertel1"]=='none'){
            	$order_data["customertel1"]="0000000000";
            }
            if($order_data['customerqq']=="UK")$order_data['customerqq']="GB";
            
            $site_root=$_SERVER['DOCUMENT_ROOT'];
            $send_xml_default_file=file_get_contents($site_root."/fuman/dhl/ShipmentRequest.xml");
            $send_xml_default_file=str_replace("<SiteID>user</SiteID>","<SiteID>".$user_conf['user_id']."</SiteID>",$send_xml_default_file);
            $send_xml_default_file=str_replace("##password##",$user_conf['pass'],$send_xml_default_file);
            $send_xml_default_file=str_replace("<Date>2015-12-01</Date>","<Date>".date("Y-m-d")."</Date>",$send_xml_default_file);
            
            if(!empty($rsdb['email'])){
                $send_xml_default_file=str_replace("<Email>test@dhl.com</Email>","<Email>".$rsdb['email']."</Email>",$send_xml_default_file);    
            }
            //$send_xml_default_file=str_replace("<Email>test@dhl.com</Email>","<Email>".date("Y-m-d")."</Email>",$send_xml_default_file);
            $send_xml_default_file=str_replace("##customer_name##",$order_data['customerid'],$send_xml_default_file);
            $send_xml_default_file=str_replace("##order_sn##",$order_data['orderID'],$send_xml_default_file);
            $send_xml_default_file=str_replace("##customerPhoneNumber##",$order_data['customertel1'],$send_xml_default_file);
            $send_xml_default_file=str_replace("##customerCity##",$order_data['customercity'],$send_xml_default_file);
            $send_xml_default_file=str_replace("##customerPostalCode##",$order_data['customerzipcode'],$send_xml_default_file);
            $send_xml_default_file=str_replace("##customerCountryName##",$order_data['customercountry'],$send_xml_default_file);
            $send_xml_default_file=str_replace("##customerCountryCode##",$order_data['customerqq'],$send_xml_default_file);
            $send_xml_default_file=str_replace("##CompanyName##",$order_data['customerid'],$send_xml_default_file);
            $send_xml_default_file=str_replace("##AddressLine##",$address1,$send_xml_default_file);
            $send_xml_default_file=str_replace("##AddressLine1##",$address2,$send_xml_default_file);
            $send_xml_default_file=str_replace("##AddressLine2##",$address3,$send_xml_default_file);
            $send_xml_default_file=str_replace("##InvoiceDate##",date("Y-m-d"),$send_xml_default_file);
            $send_xml_default_file=str_replace("##InvoiceDescription##","Costume Sample",$send_xml_default_file);
           // echo $send_xml_default_file;
			//$this->CI->fun->write_file("uploads/DHL/request".$order_data['mailNo']."-orderid".$order_data['orderID'].".xml",$send_xml_default_file);
			$send_xml_data=json_decode(json_encode(simplexml_load_string($send_xml_default_file)),TRUE);
            $result_xml=$this->call("https://xmlpi-ea.dhl.com/XMLShippingServlet",$send_xml_default_file);
            //echo $result_xml;
            //过滤各个国家的地址生僻字母
            $result_xml=preg_replace("/<AddressLine>.*?<\/AddressLine>/i","<AddressLine>{$address1}</AddressLine>",$result_xml);
            $result_xml=preg_replace("/<CompanyName>.*?<\/CompanyName>/i","<CompanyName>{$order_data[customerid]}</CompanyName>",$result_xml);
			$result_xml=preg_replace("/<PersonName>.*?<\/PersonName>/i","<PersonName>{$order_data[customerid]}</PersonName>",$result_xml);
			$result_xml=preg_replace("/<City>.*?<\/City>/i","<City>{$order_data[customercity]}</City>",$result_xml);
			
            $ret_data = json_decode(json_encode(simplexml_load_string($result_xml)),TRUE);
            //$this->CI->fun->write_file("uploads/DHL/response".$order_data['mailNo']."-orderid".$order_data['orderID'].".xml",$result_xml);
            //dump($ret_data);
            //die;
            if($ret_data['Note']['ActionNote']=='Success'){//交运成功
                $order_data['state']=1;// shipping_number,label_img,invoice_img';
                $order_data['shipping_number']=$ret_data['AirwayBillNumber'];
                $order_data['express_price']=$ret_data['Dutiable']['DeclaredValue'];
                $order_data['error_msg']='交运成功，运单号:'.$ret_data['AirwayBillNumber'];
				//保存图片到本地
				$dir = $site_root. "/uploads/dhlexpress/".date("Ymd");
				!is_dir($dir) && @mkdir($dir, 0755, true);
				$Path = $dir. "/".$order_data['orderID']."-order.pdf";
                $invoice_path= $dir. "/".$order_data['orderID']."-invoice.pdf";
                $stie_path="/uploads/dhlexpress/".date("Ymd")."/".$order_data['orderID']."-order.pdf";
                
				$content=$ret_data['LabelImage']['OutputImage'];
                $invoice_content=$ret_data['LabelImage']['MultiLabels']['MultiLabel']['DocImageVal'];
				file_put_contents($Path, base64_decode($content));
                file_put_contents($invoice_path, base64_decode($invoice_content));
				$order_data["printUrl"] = $stie_path;
                /*$open=fopen($dir."/".$order_data['orderID'].".txt","a" );
                fwrite($open,$result_xml);
                fclose($open);*/
 
				$rsdbts = $this->CI->fun->pdf2png($Path,'dhlexpress');
                if(!empty($rsdbts[0])){
                    $image_urls=implode('|',$rsdbts);
                    $order_data["label_img"] = $image_urls;    
                }
                $order_data['error_msg']='交运成功，运单号:'.$ret_data['AirwayBillNumber'].' ，运单:<a href='.$stie_path.' target="_blank">'.$stie_path.'</a><br />';
                $success+=1;
                
                if($rsdb){
                    $this->shipmentLog(array('order_id'=>$rsdb['order_id'],"mailNo"=>$ret_data['AirwayBillNumber'],"order_sn"=>$order_data['orderID']));    
                }
                
                
            }else{//交运失败
                $order_data['state']=0;// shipping_number,label_img,invoice_img';
                $order_data['shipping_number']=0;
				if($ret_data['Response']['Status']['Condition']['ConditionCode'])
				{
                $order_data['error_msg']=$ret_data['Response']['Status']['Condition']['ConditionCode'].":"
                .$ret_data['Response']['Status']['Condition']['ConditionData'];
				}
            }
            echo "交运结果<strong>$order_data[error_msg]</strong><br />";
            $express_results[]=$order_data;
        }
        //dump($express_results);
        $this->updateMabangOrder($express_results,'DHL');
        $result=array('success'=>$success,'state'=>'finish');
		return $result;
     }


    public function shipmentUBI($order_ids,$express_type='UBI澳洲'){
		//echo $this->WALLTECH_SERVER;
        $express_results=array();
        $json_body_arr=array();
        $order_data = $order_ids[0];
        $success=0;
        foreach($order_ids as $key=>$order_data){
			
			$address1 = substr($order_data["customeraddress"],0,40);
		    $address2 = substr($order_data["customeraddress"],40,40);
			$address3 = substr($order_data["customeraddress"],80,40);
            echo '开始处理'.$order_data['orderID'].'的交运..<br />';
            $sku = "";
            if($order_data['isform']==1){
                $order_data["orderID"]=str_replace("\\r",'',trim($order_data["orderID"])); 
                $goodslist = $this->db->get_where('db_mabangsell',"orderid ='".$order_data["orderID"]."'")->result_array();
    			if(count($goodslist)>0){
    			     $weight=0;
    				foreach($goodslist as $key=>$goods){
    				    $goodslist[$key]['goods_number']= $goods['ordernum']; 
                        $goodslist[$key]['goods_sn']= $goods['productid'];  
                        $goodslist[$key]['positions']= $goods['locationad'];
                        $weight +=$goods['weight'];   
    				}
                }
                $weight = $weight?$weight:400;  
                $weight = $weight / 1000;
            }else{
                $rsdb = $this->db->get_one("SELECT * FROM db_order_list WHERE order_sn='".$order_data['orderID']."'");
    			$weight = $rsdb["orderweight"]?$rsdb["orderweight"]:400;
    			$weight = $weight / 1000;
    			$goodslist = $this->CI->fun->getdatabaseslist("db_order_sell A left join db_goods_stock B
            on A.goods_id = B.goods_id"," AND A.order_id='".$rsdb["order_id"]."' and B.storage_name='一号仓'");
                 //$goodslist = $this->CI->fun->getdatabaseslist("db_order_sell A"," AND A.order_id='".$rsdb["order_id"]."'");
            }

			if(count($goodslist)>0){
				foreach($goodslist as $key=>$goods)
				{
					$sku.=$goods["goods_number"]."*".$goods["goods_sn"]."__".$goods["positions"].",";
				}
			}
			//$syd = $order_data['customerprovince'];
			$syd = $order_data['customerprovince'];
            $shipment_info=array("referenceNo"=>$order_data['orderID'],"recipientName"=>$order_data['customerid'],"addressLine1"=>$address1,
            'addressLine2'=>$address2,'addressLine3'=>$address3,"city"=>$order_data['customercity'],"state"=>$syd,"invoiceCurrency"=>"AUD","country"=>$order_data['customercountry'],
            "postcode"=>$order_data['customerzipcode'],"weight"=>$weight,"description"=>"COSTUME","nativeDescription"=>'动漫服装及配件',"invoiceValue"=>20,"shipperCity"=>"Shanghai","shipperState"=>"2,NO.1028, Hua Jiang Rd","returnCity"=>"shanghai","sku"=>$sku);
            if($address2==false){
                unset($shipment_info['addressLine2']);
            }
			 if($address3==false){
                unset($shipment_info['addressLine3']);
            }          
            $json_body_arr[]=$shipment_info;
        }
		 
        $json_body=json_encode($json_body_arr);//请求交运的订单数据
        //echo $json_body;
		$method='/services/integration/shipper/orders';
		$headers=$this->build_headers('POST', $this->WALLTECH_SERVER.$method);
		$action_ret_json=$this->send_request($method,$headers,$json_body);//运单交运
		//echo $action_ret_json;
		//echo "<-action_ret_json";
        $action_ret=json_decode($action_ret_json,true);
        //$action_ret=$this->object2array($action_ret);
		
        if($action_ret[0]['status']=='Failed' || $action_ret=='' || $action_ret['status']=='Failed'){//如果帐号异常
            echo 'UBI交运失败，失败提示：';
            if($action_ret['status']=='Failed'){
                echo $action_ret['status'].",code:".$action_ret['code'].":".$action_ret['message'];  
                $exememo = $action_ret['code'].":".$action_ret['message'];     
            }else{
                $exememo = $action_ret[0]['code'].":".$action_ret[0]['message'];   
            }
			
            if($action_ret[0]['code']=='110003'){
                $exememo='该订单编号曾被交运过,'.$exememo;
            }
            if($action_ret[0]['code']=='100007'){
                $exememo='没有可选渠道寄到该地区,'.$exememo;
            }
            if($action_ret[0]['code']=='120024'){
                $exememo='没有开通该地区的邮寄服务,'.$exememo;
            }
            echo $exememo;
			$postdata["isexe"] = 2;
            $postdata["deliver"] = $express_type;
    		$postdata["exememo"] = $exememo;
    		$postdata["mailinstime"] =time();
    		$this->db->query($this->db->update_string('db_mabangorder', $postdata, 'id=' .$order_data["id"]));
            $result=array('success'=>0,'state'=>'finish');
		    return $result;
        }
		$sendinfoid = $order_data["id"];
		$ordersn = $order_data['orderID'];
		foreach($action_ret as $key=>$ret_data){//开始处理返回的json,处理成可以入库更新的格式  
            if($ret_data['status']=='Succeeded'){//交运成功
                $ret_data["referenceNo"]=str_replace("\\r",'',trim($ret_data["referenceNo"])); 
				$newno[] = $ret_data["referenceNo"];
                
				$imgpath=$this->printUBIlabel($newno);
				    if (file_exists($imgpath['path_full'])) {
    					$rsdbts = $this->CI->fun->pdf2png($imgpath['path_full'],'ubiexpress');
                        $image_urls=implode('|',$rsdbts);
                    }else{
                        dump($imgpath);
                    }
    				$label_img = $image_urls;
      			//将货号单号、物流公司更新到订单信息
    			$update_order = "";
    			$update_order["shipping_number"] = $ret_data["trackingNo"];	//运单号
    			$update_order["shipping_time"] = time();				//交运时间
    			$update_order["shipping_name"] = $express_type;
                $shipping =$this->CI->fun->getdatabasesdetail("db_order_express"," AND name='$express_type'");
    			$update_order["shipping_id"] = $shipping["id"];
            
    			$this->db->query($this->db->update_string('db_order_list', $update_order, 'order_sn="' .$ordersn.'"'));
			 

				$postdata["isexe"] = 1;
				$postdata["printUrl"] = $imgpath['site_path'];
				$postdata["mailNo"] =$ret_data['trackingNo'];
				$postdata["originCode"] = 0;
				$postdata["destCode"] = 0;
                $postdata["deliver"] = $express_type;
				$postdata["print_img"] =$label_img;
				$postdata["exememo"] = "交运成功";
				$postdata["mailinstime"] =time();
				$this->db->query($this->db->update_string('db_mabangorder', $postdata, 'id=' .$sendinfoid));

			    $order_data['error_msg']='交运成功，运单号:'.$ret_data['trackingNo'];
                $error_msg="订单号".$ret_data['referenceNo'].' 交运成功，运单号:'.$ret_data['trackingNo'].
                ' ，运单:<a href="/'.$label_img.'" target="_blank">'.$label_img.'</a><br />';
                $success+=1;
                $rsdb = $this->db->get_one("SELECT order_id FROM db_order_list WHERE order_sn='".$ordersn."'");
                if($rsdb){
                    $this->shipmentLog(array('order_id'=>$rsdb['order_id'],"mailNo"=>$ret_data['trackingNo'],"order_sn"=>$ordersn));    
                }
            }
            echo "<strong>交运结果</strong><br />$error_msg<br />";
        }
        $result=array('success'=>$success,'state'=>'finish');
        return $result;
    }
    
    public function sureUBIexpressOrder($order_sn_list){
		$method='/services/integration/shipper/manifests/';
		$headers=$this->build_headers('POST', $this->WALLTECH_SERVER.$method);
        $order_sn_json=json_encode($order_sn_list);
		$body=$order_sn_json;
		$action_ret_json=$this->send_request($method,$headers,$body);
        //$action_ret=json_decode($action_ret_json,true);
        return $action_ret_json;
    }
 
     
    
    public function shipmentCNE($order_ids){
        date_default_timezone_set("UTC/GMT");
        $site_root=$_SERVER['DOCUMENT_ROOT'];
		$user_conf_json = stripslashes($this->CI->config->item("shipment_conf_cne"));
		$user_conf = unserialize($user_conf_json);

        $cne_user['icID']=$user_conf['user_id'];// //9031
        $CNEpass=$user_conf['pass'];//  //U2oxeMzdBPYk1vB
        $cne_user['RequestName']='PreInputSet';
        $post_data=$this->_doData($cne_user,$CNEpass);
        $express_results=array();
        $success=0;
        $json_body_arr=array();
        foreach($order_ids as $key=>$order_data){//处理符合格式的json数据
            $address1 = $order_data["customeraddress"];
			$rsdb = $this->db->get_one("SELECT * FROM db_order_list WHERE order_sn='".$order_data['orderID']."'");
			$weight = $rsdb["orderweight"]?$rsdb["orderweight"]:400;
			$weight = $weight / 1000;
			$goodslist = $this->CI->fun->getdatabaseslist("db_order_sell A"," AND A.order_id='".$rsdb["order_id"]."'");
             
			if(count($goodslist)>0){//处理配货单
                $all_goods_account=0;
                foreach($goodslist as $key=>$goods){
                    $all_goods_account+=$goods["goods_number"];
                }
                $good_price=round(9.99/$all_goods_account,2);
				foreach($goodslist as $key=>$goods)
				{
				    $stockinfo=$this->CI->fun->getdatabasesdetail('db_goods_stock'," AND goods_id='".$goods["goods_id"]."' AND storage_id = 1");
                    $goodinfo = $this->CI->fun->getdatabasesdetail("db_goods"," AND goods_id=".$goods['goods_id']);
				    $goods_name=$stockinfo['storage_name']."__".$stockinfo["positions"]."__库存".$stockinfo['stock']."__".$goodinfo['goods_name'];
                    $en_goods_name=$goodinfo['en_goods_name']==''?'Costume accessories':substr($goodinfo['en_goods_name'],0,60);
                    $goods['price']=$good_price;
                    $goods['price']=$goods['price']<=0?0.01:$goods['price'];
                    $goods["positions"]=$goods["positions"]==''?"_":$goods["positions"];
                    $goodsinfo=array("cxGoods"=>$goods_name,"cxGoodsA"=>$en_goods_name,
                    "cxGCodeA"=>$goods["goods_sn"],"ixQuantity"=>$goods["goods_number"],"fxPrice"=>$goods['price']);
				    $GoodsList[]=$goodsinfo;
                }
			}
            //CNE全球通挂号
            $order_data['deliver']=$order_data['deliver']==''?'CNE全球通挂号':$order_data['deliver'];
            $reclist_detail=array("iID"=>0,"nItemType"=>1,"cRNo"=>$order_data['orderID'],"cDes"=>$order_data['customerqq'],"cEmsKind"=>$order_data['deliver'],
            "fWeight"=>$weight,"cReceiver"=>$order_data['customerid'],"cRPhone"=>$order_data['customertel1'],"cRPostcode"=>$order_data['customerzipcode'],
            "cRCountry"=>$order_data['customercountry'],"cRProvince"=>$order_data['customerprovince'],"cRCity"=>$order_data['customercity'],
            "cRAddr"=>$address1);
            $reclist_detail['GoodsList']=$GoodsList;
            $post_data['RecList'][]=$reclist_detail; 
        }
        $post_json_data=json_encode($post_data);
        if($order_data['orderID']=='3230506325838614712'){
            //dump($post_json_data);
            //die;   
        }
        //dump($post_json_data);
        $result_json=$this->requestPost("http://api.cnexps.com/cgi-bin/EmsData.dll?DoApi",$post_json_data);
       // echo $result_json;
        $ret_data=json_decode($result_json);
        $action_ret=$this->object2array($ret_data);
       // echo '接口返回：';
        //echo $result;

		if($action_ret['ReturnValue']==1){//交运成功
    		foreach($action_ret['ErrList'] as $key=>$ret_data){//开始处理返回的json,处理成可以入库更新的格式
                $order_data=$order_ids[$key];//对应提前的订单数据 
                $sendinfoid = $order_data["id"]; 
                $ordersn = $order_data['orderID'];
                if($ret_data['iID']<1){//交运异常，没有存入服务器
                    echo '订单'.$order_data.'交运失败，失败提示：';
                    echo $ret_data['cMess'];
        			$exememo = $ret_data['cMess'];
        			$postdata["isexe"] = 2;
            		$postdata["exememo"] = $exememo;
            		$postdata["mailinstime"] =time();
            		$this->db->query($this->db->update_string('db_mabangorder', $postdata, 'id=' .$order_data["id"]));
                    $result=array('success'=>0,'state'=>'finish');
        	
                }else{
    				$newno[] = $ret_data["referenceNo"];
                    $label_param_signature= md5($cne_user['icID'].$ret_data['cNum'].$CNEpass);
                    $label_param_icID=$cne_user['icID'];
                    $label_param_cNums=$ret_data['cNum'];
                    $label_param_ptemp='label10x10_1';//打印标签样式
                    $label_img_url="http://label.cnexps.com/CnePrint?icID=$label_param_icID&cNums=$label_param_cNums&ptemp=$label_param_ptemp&signature=$label_param_signature";
                    //echo $label_img_url;
                    /*下载pdf标签---------------------
                    $dir = $site_root. "/uploads/cneexpress/".date("Ymd");
    				!is_dir($dir) && @mkdir($dir, 0755, true);
    				$Path = $dir. "/".$ordersn."-order.pdf";
                    $stie_path="/uploads/cneexpress/".date("Ymd")."/".$ordersn."-order.pdf";
                    $content=file_get_contents($label_img_url);//下载到内存
                    file_put_contents($Path, $content);
                    $ret_data['label_pdf_path']=$stie_path;
    				$ret_data["label_img"] = $stie_path;
    				$rsdbts = $this->CI->fun->pdf2png($Path,'cneexpress');
                    if(!empty($rsdbts[0])){
                        $image_urls=implode('|',$rsdbts);
                        $ret_data["label_img"] = $image_urls;    
                    }
                    ---------------------------*下载pdf标签结束*/
          			//将货号单号、物流公司更新到订单信息
        			$update_order = "";
        			$update_order["shipping_number"] = $ret_data["cNum"];	//运单号
        			$update_order["shipping_time"] = time();				//交运时间
        			$update_order["shipping_name"] = $order_data['deliver'];
                    $express_type=$order_data['deliver'];
                    $shipping =$this->CI->fun->getdatabasesdetail("db_order_express"," AND name='$express_type'");
        			$update_order["shipping_id"] = $shipping["id"];
        			$this->db->query($this->db->update_string('db_order_list', $update_order, 'order_sn="' .$ordersn.'"'));
    			
    				$postdata["isexe"] = 1;
    			//	//$postdata["printUrl"] = $ret_data['label_pdf_path'];  pdf调整
    				$postdata["mailNo"] =$ret_data['cNum'];
    				$postdata["originCode"] = 0;
    				$postdata["destCode"] = 0;
    			//	$postdata["print_img"] =$ret_data["label_img"];   pdf调整
    				$postdata["exememo"] = "交运成功";
    				$postdata["mailinstime"] =time();
    				$this->db->query($this->db->update_string('db_mabangorder', $postdata, 'id=' .$sendinfoid));
    
    			    $order_data['error_msg']='交运成功，运单号:'.$ret_data['cNum'];
                    $error_msg="订单号".$ordersn.' 交运成功，运单号:'.$ret_data['cNum'].
                    ' ，运单:<a href="'.$ret_data["label_pdf_path"].'" target="_blank">'.$ret_data["label_pdf_path"].'</a><br />';
                    echo "<strong>交运结果</strong><br />$error_msg<br />";
                    $rsdb = $this->db->get_one("SELECT order_id FROM db_order_list WHERE order_sn='".$ordersn."'");
                    $this->shipmentLog(array('order_id'=>$rsdb['order_id'],"mailNo"=>$ret_data['cNum'],"order_sn"=>$ordersn));
                    $result=array('success'=>1,'state'=>'finish');
                }
            }
        }else{
            echo 'CNE交运失败，失败提示：';
            echo $result_json;  
            $ret_data=json_decode($result_json);
            dump($ret_data);
            $result=array('success'=>0,'state'=>'finish');
        }
        return $result;
    }
    
	public function getYIDAgettrack($tracking_number,$type='')
	{

		$post_data['appToken']="21db062ff076b8a19bb50e84ea45f7de";// //9031
        $post_data['appKey']="5ea6903578230e2d2bcdc12135adcdca5ea6903578230e2d2bcdc12135adcdca";
        $post_data['serviceMethod']='gettrack';
		$express_results=array();
		
		$post_data['tracking_number']=trim($tracking_number);
		$post_data['paramsJson']=json_encode($post_data);
        
		$post_json_data=json_encode($post_data);
		
		$result_json=$this->requestYIDAPost("http://customer.ydhex.com/webservice/PublicService.asmx/ServiceEntrance",$post_json_data);
        $ret_data=json_decode($result_json,true);
		
        $action_ret=json_decode($ret_data['d'],true);
		
		if($type =='Test')
		{
			echo "<xmp>";
			print_r($action_ret);
			echo "</xmp>";
			die;
		}
		if($action_ret['success'] ==1)
		{
			$details  = $action_ret['data'][0]['details'];
			

			foreach($details as $key=>$rs)
			{
				if($rs['track_description'] =='引受')
				{
					return true;
				}
			}

			return false;
		}else{
			return false;
		}
	}
    
    public function shipmentYIDA($order_ids){

        $site_root=$_SERVER['DOCUMENT_ROOT'];
		//$user_conf_json = stripslashes($this->CI->config->item("shipment_conf_cne"));
		//$user_conf = unserialize($user_conf_json);
        $post_data['appToken']="21db062ff076b8a19bb50e84ea45f7de";// //9031
        $post_data['appKey']="5ea6903578230e2d2bcdc12135adcdca5ea6903578230e2d2bcdc12135adcdca";
        $post_data['serviceMethod']='createorder';

        $express_results=array();
        $success=0;
        $json_body_arr=array();
        foreach($order_ids as $key=>$order_data){//处理符合格式的json数据
            $address1 = $order_data["customeraddress"];
			$rsdb = $this->db->get_one("SELECT * FROM db_order_list WHERE order_sn='".$order_data['orderID']."'");
			$weight = $rsdb["orderweight"]?$rsdb["orderweight"]:400;
			$weight = $weight / 1000;
            $shipment_orderid=$order_data['exememo']=='参考号码已经存在'?$order_data['orderID']."-01":$order_data['orderID'];
            $json_body_arr=array("reference_no"=>$shipment_orderid,"shipping_method"=>"JP-DS POST",  "order_weight"=>$weight,
             "order_pieces"=>"1","mail_cargo_type"=>"4", "return_sign"=>"", "buyer_id"=>"", "order_info"=>"备注"); 
             
			$goodslist = $this->CI->fun->getdatabaseslist("db_order_sell A left join db_goods_stock B
             on A.goods_id = B.goods_id"," AND A.order_id='".$rsdb["order_id"]."'");
			if(count($goodslist)>0){//处理配货单
				foreach($goodslist as $key=>$goods){
				    $goods_name=$goods['goods_name']."__".$goods['storage_name']."__".$goods["positions"];//."__[".$goods["positions"]."]"
                    $goods['price']=round($goods['costprice']/6.3, 2);
                    $goods['price']=$goods['price']<=0?0.01:$goods['price'];
                    $goods["positions"]=$goods["positions"]==''?"_":$goods["positions"];
                    $goodsinfo=array("invoice_enname"=>"Costume accessorles", "invoice_cnname"=>$goods_name, "invoice_quantity"=>"1",
    "invoice_unitcharge"=>$goods['price'], "unit_code"=>"PCE");
				    $json_body_arr['invoice'][]=$goodsinfo;
                }
			}
            
            $shipper=array("shipper_name"=>"Chen Xiao", "shipper_company"=>"Shanghai Fu Man Ltd,CO.", "shipper_countrycode"=>"CN",
             "shipper_street"=>"Floor 6,Building 2,NO.1028, Hua Jiang Rd,","shipper_city"=>"Shanghai", "shipper_province"=>"Shanghai", "shipper_areacode"=>"11",
            "shipper_postcode"=>"200803", "shipper_telephone"=>"59157928", "shipper_mobile"=>"");
            $consignee=array("consignee_name"=>$order_data['customerid'], "consignee_company"=>$order_data['customercountry'], "consignee_countrycode"=>"JP", 
            "consignee_street"=>$address1, "consignee_city"=>$order_data['customercity'], "consignee_province"=>$order_data['customerprovince'],
            "consignee_areacode"=>"", "consignee_postcode"=>$order_data['customerzipcode'], "consignee_telephone"=>$order_data['customertel1'], "consignee_mobile"=>"","consignee_email"=>"",
"consignee_fax"=>"", "consignee_certificatetype"=>"", "consignee_certificatecode"=>"", "consignee_credentials_period"=>"");
            
            $json_body_arr['shipper']=$shipper;
            $json_body_arr['consignee']=$consignee;
            //$json_body_arr['invoice']=$GoodsList;
            $json_body_arr['extra_service']=array();
            $post_data['paramsJson']=json_encode($json_body_arr); 
        }
        $post_json_data=json_encode($post_data);
        //echo json_encode($post_data);
        //$post_info_str="appToken=$post_data[appToken]&appKey=$post_data[appKey]&serviceMethod=createorder&paramsJson=$post_data[paramsJson]";
        //dump($post_data);
        $result_json=$this->requestYIDAPost("http://customer.ydhex.com/webservice/PublicService.asmx/ServiceEntrance",$post_json_data);
        $ret_data=json_decode($result_json,true);
        $action_ret=json_decode($ret_data['d'],true);;
        $ret_data=$action_ret['data'];
       // echo '<br />接口返回：';
        //echo $result_json;
        //echo "<br /><br />";
    //dump($this->pintrYIDALabel('267424061385532'));
        $order_data=$order_ids[0];//对应提前的订单数据 
        $sendinfoid = $order_data["id"]; 
        $ordersn = $order_data['orderID'];
        if($action_ret['success']<1){//交运异常，没有存入服务器
            echo '订单'.$ordersn.'交运失败，失败提示：';
            echo $action_ret['cnmessage'];
			$exememo = $action_ret['cnmessage'];
			$postdata["isexe"] = 2;
    		$postdata["exememo"] = $exememo;
    		$postdata["mailinstime"] =time();
    		$this->db->query($this->db->update_string('db_mabangorder', $postdata, 'id=' .$order_data["id"]));
            $result=array('success'=>0,'state'=>'finish');
		    return $result;
        }else{
            $ret_data["cNum"]=$ret_data['shipping_method_no'];
            $label_img_url=$this->pintrYIDALabel($ordersn);
            //echo $label_img_url;
            $dir = $site_root. "/uploads/yidaexpress/".date("Ymd");
			!is_dir($dir) && @mkdir($dir, 0755, true);
			$Path = $dir. "/".$ordersn."-order.png";
            $stie_path="uploads/yidaexpress/".date("Ymd")."/".$ordersn."-order.png";
            $content=file_get_contents($label_img_url);//下载到内存
            file_put_contents($Path, $content);
            //$stie_path=$label_img_url;
            $ret_data['label_pdf_path']='/'.$stie_path;
            //echo '运单:<a href="'.$ret_data["label_pdf_path"].'" target="_blank">'.$ret_data["label_pdf_path"].'</a><br />';
			$ret_data["label_img"] = $stie_path;
			//$rsdbts = $this->CI->fun->pdf2png($Path);
            //if(!empty($rsdbts[0])){
            //    $image_urls=implode('|',$rsdbts);
            //    $ret_data["label_img"] = $image_urls;    
            //}
  			//将货号单号、物流公司更新到订单信息
			$update_order = "";
			$update_order["shipping_number"] = $ret_data["cNum"];	//运单号
			$update_order["shipping_time"] = time();				//交运时间
			$update_order["shipping_name"] = $order_data['deliver'];
            $express_type=$order_data['deliver'];
            $shipping =$this->CI->fun->getdatabasesdetail("db_order_express"," AND name='$express_type'");
			$update_order["shipping_id"] = $shipping["id"];
			$this->db->query($this->db->update_string('db_order_list', $update_order, 'order_sn="' .$ordersn.'"'));
		
			$postdata["isexe"] = 1;
			$postdata["printUrl"] = $ret_data['label_pdf_path'];
			$postdata["mailNo"] =$ret_data['cNum'];
			$postdata["originCode"] = 0;
			$postdata["destCode"] = 0;
			$postdata["print_img"] =$ret_data["label_img"];
			$postdata["exememo"] = "交运成功";
			$postdata["mailinstime"] =time();
			$this->db->query($this->db->update_string('db_mabangorder', $postdata, 'id=' .$sendinfoid));

		    $order_data['error_msg']='交运成功，运单号:'.$ret_data['cNum'];
            $error_msg="订单号".$ordersn.' 交运成功，运单号:'.$ret_data['cNum'].
            ' ，运单:<a href="../'.$ret_data["label_pdf_path"].'" target="_blank">'.$ret_data["label_pdf_path"].'</a><br />';
            echo "<strong>交运结果</strong><br />$error_msg<br />";
            $rsdb = $this->db->get_one("SELECT order_id FROM db_order_list WHERE order_sn='".$ordersn."'");
            $this->shipmentLog(array('order_id'=>$rsdb['order_id'],"mailNo"=>$ret_data['cNum'],"order_sn"=>$ordersn));
            $result=array('success'=>1,'state'=>'finish');
        }
        return $result;
    }
    
    
    //中通交运
    public function shipmentZTO($orders){
        $orderinfo=$orders[0];
        $zturl='http://japi.zto.cn/partnerInsertSubmitagent';
        $headers = array(
        'ContentType:application/x-www-form-urlencoded',
        'x-companyId:92c3253a4df14881bce9d3bb49bf7cf1');
        $rsdb = $this->db->get_one("SELECT * FROM db_order_list WHERE order_sn='".$orderinfo['orderID']."'");
		$weight = $rsdb["orderweight"]?$rsdb["orderweight"]:400;
		$weight = $weight / 1000;
             
        $post_data['company_id']="92c3253a4df14881bce9d3bb49bf7cf1";// //9031
        $post_data['msg_type']="submitAgent";
        $bodyinfo=array("partner"=>'ZTO531520902670519','id'=>$orderinfo['orderID'],'typeid'=>1,
            'tradeid'=>$rsdb['tradeid'],'buyer'=>$rsdb['customerid'],'weight'=>$weight,
            'sender'=>array('name'=>'漫创旗舰店','mobile'=>'18049897965','city'=>'上海市','address'=>'嘉定区华江路1028号蒂莎创意园2号楼5楼'),
            'receiver'=>array('name'=>$orderinfo['customerid'],'mobile'=>$orderinfo['customertel1'],'phone'=>'0',
            'city'=>$orderinfo['customercity'],'address'=>$orderinfo['customeraddress'],'zipcode'=>$orderinfo['customerzipcode']),
        );
        $post_data['data']=json_encode($bodyinfo);
        foreach($post_data as $key=>$val){
            $strParam.=$key."=".$val."&";
        }
        $strParam=trim($strParam,'&');
        $secret_sign=base64_encode(md5($strParam."7ddffda6c7cf",true));
        $headers[]="x-dataDigest:$secret_sign";
        $result =$this->ZTOHttpRequest($zturl,$headers,$strParam);
        $ordersn=$orderinfo['orderID'];
     
        $action_ret=json_decode($result,true);
        $ret_data=$action_ret['data'];
        $label_arr=$this->pintrZTOLabel($orderinfo,$rsdb,$ret_data['billCode']);
        $bagaddr=$label_arr["result"]['bagAddr'];
        $mark_number=explode(" ",$label_arr["result"]['mark']);
        
        if($action_ret['result']==false || $bagaddr=='' || $mark_number[1]==''){//交运异常，没有存入服务器
            echo '订单'.$ordersn.'交运失败，失败提示：';
            echo $ret_data['message'];
            if($bagaddr=='' || $mark_number[1]==''){
                $ret_data['message']='大头笔或集包地获取失败，可能原因：收货地址异常';   
            }
			$exememo = $ret_data['message'];
			$postdata["isexe"] = 2;
    		$postdata["exememo"] = $exememo;
    		$postdata["mailinstime"] =time();
    		$this->db->query($this->db->update_string('db_mabangorder', $postdata, 'id=' .$orderinfo["id"]));
            $result=array('success'=>0,'state'=>'finish');
		    return $result;
        }else{
            $ret_data["cNum"]=$ret_data['billCode'];


  			//将货号单号、物流公司更新到订单信息
			$update_order = "";
			$update_order["shipping_number"] = $ret_data["cNum"];	//运单号
			$update_order["shipping_time"] = time();				//交运时间
			$update_order["shipping_name"] = $orderinfo['deliver'];
            $express_type=$orderinfo['deliver'];
            $shipping =$this->CI->fun->getdatabasesdetail("db_order_express"," AND name='$express_type'");
			$update_order["shipping_id"] = $shipping["id"];
			$this->db->query($this->db->update_string('db_order_list', $update_order, 'order_sn="' .$ordersn.'"'));
		
			$postdata["isexe"] = 1;
			//$postdata["printUrl"] = $label_arr['label_pdf'];
			$postdata["mailNo"] =$ret_data['cNum'];
			$postdata["originCode"] = 0;
			$postdata["destCode"] = 0;
			//$postdata["print_img"] =$label_arr["label_img"];
            $postdata["content1"] =$label_arr["result"]['mark']."||".$label_arr["result"]['bagAddr'];
			$postdata["exememo"] = "交运成功";
			$postdata["mailinstime"] =time();
			$this->db->query($this->db->update_string('db_mabangorder', $postdata, 'id=' .$orderinfo['id']));
            $error_msg="订单号".$ordersn.' 交运成功，运单号:'.$ret_data['cNum'].
            ' ，运单:<a href="/expressshipment/ajaxbutton?op=printlabel&orderType=14&id='.$orderinfo["id"].'" target="_blank">'.$ret_data["cNum"].'</a><br />';
            echo "<strong>交运结果</strong><br />$error_msg<br />";
            $rsdb = $this->db->get_one("SELECT order_id FROM db_order_list WHERE order_sn='".$ordersn."'");
            $this->shipmentLog(array('order_id'=>$rsdb['order_id'],"mailNo"=>$ret_data['cNum'],"order_sn"=>$ordersn));
            $result=array('success'=>1,'state'=>'finish');
        }
        return $result;
    }

    public function pintrZTOLabel($orderinfo,$shipinfo,$mailNo){
        $zturl='http://japi.zto.cn/bagAddrMarkGetmark';
        //获取大头笔
        $headers = array(
        'ContentType:application/x-www-form-urlencoded',
        'x-companyId:92c3253a4df14881bce9d3bb49bf7cf1');
        $rsdb = $this->db->get_one("SELECT * FROM db_order_list WHERE order_sn='".$orderinfo['orderID']."'");
		$weight = $rsdb["orderweight"]?$rsdb["orderweight"]:400;
		$weight = $weight / 1000;
        
        $receive_district=current(explode(' ',$orderinfo['customeraddress']));    
        $post_data['company_id']="92c3253a4df14881bce9d3bb49bf7cf1";// //9031
        $post_data['msg_type']="GETMARK";
        $bodyinfo=array('unionCode'=>$mailNo,'send_province'=>'上海',
            'send_city'=>'上海市','send_district'=>'嘉定区','receive_province'=>$orderinfo['customerprovince'],
            'receive_city'=>$orderinfo['customercity'],'receive_district'=>$receive_district,'receive_address'=>$orderinfo['customeraddress']
        );

        $post_data['data']=json_encode($bodyinfo);
        foreach($post_data as $key=>$val){
            $strParam.=$key."=".$val."&";
        }
        $strParam=trim($strParam,'&');
        $secret_sign=base64_encode(md5($strParam."7ddffda6c7cf",true));

        $headers[]="x-dataDigest:$secret_sign";
        $result =$this->ZTOHttpRequest($zturl,$headers,$strParam);

        
        $action_ret=json_decode($result,true);

        
        
        return $action_ret;
    }
    
    function ZTOHttpRequest($url, $headers, $post_fields) {
        $args = array();
        $connection = curl_init($url);            
        $curl_options = array(CURLOPT_HTTPHEADER=>$headers, CURLOPT_POSTFIELDS=>$post_fields,
        CURLOPT_SSLVERSION=>CURL_SSLVERSION_TLSv1, CURLOPT_SSL_CIPHER_LIST =>"TLSv1",
        CURLOPT_SSL_VERIFYPEER=>false,
        CURLOPT_POST=>1, CURLOPT_RETURNTRANSFER=>1);  # data will be returned as a string
        curl_setopt_array($connection, $curl_options);
        $json_response = curl_exec($connection);
        if (curl_errno($connection) > 0) {
          echo curl_error($connection) . "\n";
          exit(2);
        }
        curl_close($connection);
        return $json_response;
    }
    
    
    
    
    public function shipmentJiAC($order_ids){//佳成物流
        $site_root=$_SERVER['DOCUMENT_ROOT'];
        $json_body_arr=array();
        $json_body_arr['apiplatform']="复漫网络";// //9031
        $json_body_arr['jcexkey']="NET2";
        $json_body_arr['customerid']='39E1B837-E445-4A3D-9D01-9564B4D7327D';
        $json_body_arr['customer']='SH0931';

        $express_results=array();
        $success=0;
        foreach($order_ids as $key=>$order_data){//处理符合格式的json数据
            $address1 = $order_data["customeraddress"];
			$rsdb = $this->db->get_one("SELECT * FROM db_order_list WHERE order_sn='".$order_data['orderID']."'");
			$weight = $rsdb["orderweight"]?$rsdb["orderweight"]:600;
			$weight = $weight / 1000;
            $shipment_orderid=$order_data['exememo']=='参考号码已经存在'?$order_data['orderID']."-01":$order_data['orderID'];
            $body_arr=array("referencenumber"=>$shipment_orderid,"productid"=>"PK0746",  "productname"=>'佳成小包-佳邮宝(华东区)',
             "weightinformation"=>array(
                array("totalpackages"=>1,"itemtype"=>1,"totalweight"=>$weight,),
             ),
             'detailpackage'=>array(
                 array("actualweight"=>$weight,"length"=>10,"width"=>10,"height"=>5,'volume'=>0,'volumeweight'=>0,
                    'item'=>array(
                        array('englishname'=>'Costume Accessories','hscode'=>'61032300','inpieces'=>1,"unitpriceamount"=>16,
                            "unitpriceweight"=>$weight,
                            "declarationamount"=>16,
                            "declarationcurrency"=>"USD"
                        ),
                    )
                 ),
             ),
             'invoiceinformation'=>array(
                array("chinesename"=>"动漫服装周边及配件","englishname"=>"Costume Accessories","hscode"=>"61032300",
                "inpieces"=>"1","unitpriceamount"=>15.99,"declarationamount"=>15.99,"declarationcurrency"=>"USD"),
             ),
             'recipientinformation'=>array(
                 array("recipientname"=>$order_data['customerid'],"recipientphone"=>$order_data['customertel1'],
                 "recipientcountry"=>$order_data['customerqq'],"recipientpostcode"=>$order_data['customerzipcode'],
                 "recipientcity"=>$order_data['customercity'],"recipientstate"=>$order_data['customerprovince'],
                 "recipienttown"=>"","recipientaddress"=>$address1,"recipientcompany"=>""),
             ),  
             'senderinformation'=>array(
                 array("sendername"=>"ChaoZheng","senderchinesename"=>"上海复漫网络科技有限公司",//862159157928
                    "sendercompany"=>"Shanghai Fu Man Ltd,CO.","senderphone"=>"8613818476032","sendercountry"=>"CN",
                    "sendercity"=>"shanghai","sendertown"=>"","senderpostcode"=>"201803","senderaddress"=>"Floor 6,Building 2,NO.1028, Hua Jiang Rd",
                 ),
             ),
             'specialservice'=>array(
             
             ),
            );

              
			$goodslist = $this->CI->fun->getdatabaseslist("db_order_sell A left join db_goods_stock B
             on A.goods_id = B.goods_id"," AND A.order_id='".$rsdb["order_id"]."'");
			if(count($goodslist)>0){//处理配货单
				foreach($goodslist as $key=>$goods){
				    $goods_name=$goods['goods_name']."__".$goods['storage_name']."__".$goods["positions"];//."__[".$goods["positions"]."]"
                    $goods['price']=round($goods['costprice']/6.3, 2);
                    $goods['price']=$goods['price']<=0?0.01:$goods['price'];
                    $goods["positions"]=$goods["positions"]==''?"_":$goods["positions"];
                    $goodsinfo=array("invoice_enname"=>"Costume accessorles", "invoice_cnname"=>$goods_name, "invoice_quantity"=>"1",
    "invoice_unitcharge"=>$goods['price'], "unit_code"=>"PCE");
				    //$json_body_arr['invoice'][]=$goodsinfo;
                   
                }
			}
            $json_body_arr['packages']=array($body_arr);
        }
        $post_body_data=array();
        $post_body_data['Data']=$json_body_arr;
        $json_body_arr=$post_body_data;
        echo json_encode($json_body_arr);
        $post_data['service']="orders";
        $post_data['data_body']=base64_encode(json_encode($json_body_arr)); 
        //dump($json_body_arr);
        $result_json=$this->requestPost("http://api.jcex.com/JcexJson/api/notify/sendmsg?service=orders&data_body=".$post_data['data_body'],$post_data);
        echo $result_json;
        $result_data=json_decode($result_json,true);
        //dump($result_data);
        
        //print_r($result_data);//返回结果
        
        $action_ret=$result_data['data'][0];
        $ship_result=$result_data['data'][2];
        $order_data=$order_ids[0];//对应提前的订单数据 
        $sendinfoid = $order_data["id"]; 
        $ordersn = $order_data['orderID'];
        if($ship_result['resultcode']!='success'){//交运异常，没有存入服务器
            echo '订单'.$ordersn.'交运失败，失败提示：';
            echo $ship_result['msg'];
			$exememo = $ship_result['msg'];
            if($exememo=='见outputs内容'){
                $exememo=$action_ret['outputs'];
            }
			$postdata["isexe"] = 2;
    		$postdata["exememo"] = $exememo;
            
    		$postdata["mailinstime"] =time();
    		$this->db->query($this->db->update_string('db_mabangorder', $postdata, 'id=' .$order_data["id"]));
            $result=array('success'=>0,'state'=>'finish');
		   // return $result;
        }else{
            $ret_data["cNum"]=$action_ret['waybillnumber'];
            $label_img_url=$result_data['data'][1]['jcexwaybillurl'];
            //echo $label_img_url;
            $dir = $site_root. "/uploads/jiacexpress/".date("Ymd");
			!is_dir($dir) && @mkdir($dir, 0755, true);
			$Path = $dir. "/".$ordersn."-order.pdf";
            $stie_path="uploads/jiacexpress/".date("Ymd")."/".$ordersn."-order.pdf";
            $content=$action_ret['Label'][0]['LabelZPL'];
            $retimg=base64_decode($content);
            $content=file_get_contents($label_img_url);//下载到内存
            file_put_contents($Path, $content);
            //file_put_contents($Path, $content);
            
            $ret_data['label_pdf_path']='/'.$stie_path;
			$ret_data["label_img"] = $stie_path;
            
			$rsdbts = $this->CI->fun->pdf2png($Path);
            if(!empty($rsdbts[0])){
                $image_urls=implode('|',$rsdbts);
                $ret_data["label_img"] = $image_urls;    
            }
  			//将货号单号、物流公司更新到订单信息
			$update_order = "";
			$update_order["shipping_number"] = $ret_data["cNum"];	//运单号
			$update_order["shipping_time"] = time();				//交运时间
			$update_order["shipping_name"] = $order_data['deliver'];
            $express_type=$order_data['deliver'];
            $shipping =$this->CI->fun->getdatabasesdetail("db_order_express"," AND name='$express_type'");
			$update_order["shipping_id"] = $shipping["id"];
			$this->db->query($this->db->update_string('db_order_list', $update_order, 'order_sn="' .$ordersn.'"'));
		
			$postdata["isexe"] = 1;
			$postdata["printUrl"] = $ret_data['label_pdf_path'];
			$postdata["mailNo"] =$ret_data['cNum'];
			$postdata["originCode"] = 0;
			$postdata["destCode"] = 0;
			$postdata["print_img"] =$ret_data["label_img"];
			$postdata["exememo"] = "交运成功";
			$postdata["mailinstime"] =time();
			$this->db->query($this->db->update_string('db_mabangorder', $postdata, 'id=' .$sendinfoid));

		    $order_data['error_msg']='交运成功，运单号:'.$ret_data['cNum'];
            $error_msg="订单号".$ordersn.' 交运成功，运单号:'.$ret_data['cNum'].
            ' ，运单:<a href="../'.$ret_data["label_pdf_path"].'" target="_blank">'.$ret_data["label_pdf_path"].'</a><br />';
            echo "<strong>交运结果</strong><br />$error_msg<br />";
            $rsdb = $this->db->get_one("SELECT order_id FROM db_order_list WHERE order_sn='".$ordersn."'");
            $this->shipmentLog(array('order_id'=>$rsdb['order_id'],"mailNo"=>$ret_data['cNum'],"order_sn"=>$ordersn));
            $result=array('success'=>1,'state'=>'finish');
        }
       return $result;
    }
    
    public function pintrYIDALabel($reference_no){
        $post_data['appToken']="21db062ff076b8a19bb50e84ea45f7de";// //9031
        $post_data['appKey']="5ea6903578230e2d2bcdc12135adcdca5ea6903578230e2d2bcdc12135adcdca";
        $post_data['serviceMethod']='getnewlabel';
        $configInfo=array("lable_file_type"=>1,'lable_paper_type'=>1,'lable_content_type'=>1,
            'additional_info'=>array('lable_print_invoiceinfo'=>"N",'able_print_buyerid'=>"N",'lable_print_datetime'=>'Y','customsdeclaration_print_actualweight'=>"N")
        );
        $listorder=array(array("reference_no"=>$reference_no));

        $json_body_arr=array("listorder"=>$listorder,"configInfo"=>$configInfo); 
        $post_data['paramsJson']=json_encode($json_body_arr);
        
        $post_json_data=json_encode($post_data); 
       
        $info=json_encode($test_arr);
        //dump(json_decode($info));
        
        $imginfo=$this->requestYIDAPost("http://customer.ydhex.com/webservice/PublicService.asmx/ServiceEntrance",$post_json_data);
       // dump(json_decode($imginfo,true));
        $imginfo=json_decode($imginfo,true);
        $imginfo=json_decode($imginfo['d'],true);
        $imginfo= $imginfo['data'][0]['lable_file'];
        return $imginfo;
    }


    
    /**
     * Call DHL Service
     * @param Request $request Request to send
     * 
     * @return string DHL XML response string
     */
    public function call($url,$request){
        if (!$ch = curl_init()){
            throw new \Exception('could not initialize curl');
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_PORT , 443);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$request);
        $result = curl_exec($ch);
        
        if (curl_error($ch))
        {
            return false;
        }
        else
        {
            curl_close($ch);
        }

        return $result;
    }
    
    //处理参数
    private function _doData($data,$CNEpass){
        $data['TimeStamp'] = $this->_getMicroTime();
        $keyArr = array_keys($data);
        $str = md5($data['icID'].$data['TimeStamp'].$CNEpass);
        $data['MD5'] = $str;
        return $data;

    }
    
    
    
    private function _getMicroTime(){
        list($t1, $t2) = explode(' ', microtime());
        $time=(float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
        $time=$time-28800000;
        return $time;
    }
    
    public function object2array(&$object) {
        if (is_object($object)) {
            $arr = (array)($object);
        } else {
            $arr = &$object;
        }
        if (is_array($arr)) {
            foreach($arr as $varName => $varValue){
                $arr[$varName] = $this->object2array($varValue);
            }
        }
        return $arr;
    }


	//post
	public function requestPost($url,$data=array(),$ssl=false){
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_URL,$url);//url
		//代理信息
		$user_agent = isset($_SERVEN['HTTP_USER_AGENT']) ? $_SERVEN['HTTP_USER_AGENT'] : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0';
		curl_setopt($ch,CURLOPT_USERAGENT,$user_agent);
		//请求来源
		curl_setopt($ch,CURLOPT_AUTOREFERER,true);
		if($ssl){
			//禁用后curl将终止服务端进行验证
			curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
			//检查服务器ssl证书中是否存在一个公用名
			curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);
		}
		//处理post相关
		curl_setopt($ch,CURLOPT_POST,1);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
		//是否处理响应头
		curl_setopt($ch,CURLOPT_HEADER,false);
		//是否返回响应主体
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
		//http 版本
		//curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
		$server_output = curl_exec ($ch);
		//echo curl_error($ch);
		curl_close($ch);
		if($server_output){
			return $server_output;
		}else{
			return false;
		}
	}
	//
	public function requestYIDAPost($url,$data=array()){
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');  
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if(strpos($url,"ttps")>0){
    		//禁用后curl将终止服务端进行验证
    		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
    		//检查服务器ssl证书中是否存在一个公用名
    		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);
        }
		$headers=array('Content-Type:  application/json');
		curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);   
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		$response= curl_exec($ch);
        return $response;
	}
    
    
    //更新交运结果回来
    public function updateMabangOrder($express_ret_arr,$express_type){
        //$express_ret_arr format:'mabangorder_id order_id state error_msg shipping_number,label_img,invoice_img';
        $send_ret=$express_ret_arr;
        foreach($send_ret as $key=>$sendinfo){
            $oldshipinfo=$this->CI->fun->getdatabasesdetail("db_mabangorder",'and id='.$sendinfo["id"]);
            if($oldshipinfo["isexe"]!=1){
                if($sendinfo['state']==1){//交运成功
        			$exememo = '交运成功';
        			$postdata["isexe"] = 1;
        			$postdata["mailNo"] = $sendinfo['shipping_number'];
        			$postdata["originCode"] = 0;
        			$postdata["destCode"] = 0;
                    $postdata['printUrl']=$sendinfo['printUrl'];
        			$postdata["print_img"] =$sendinfo['label_img'];
                    $postdata["deliver"] = $express_type;
        			//将货号单号、物流公司更新到订单信息
        			$update_order = "";
        			$update_order["shipping_number"] = $sendinfo["shipping_number"];	//运单号
        			$update_order["shipping_time"] = time();				//交运时间
        			$update_order["shipping_name"] = $express_type;
        			$shipping =$this->CI->fun->getdatabasesdetail("db_order_express"," AND name='$express_type'");
        			$update_order["shipping_id"] = $shipping["id"];
        			//$update_order["shipping_expectfee"] = $sendinfo['express_price'];//货去价格
        			$this->db->query($this->db->update_string('db_order_list', $update_order, 'order_sn="' .$sendinfo["orderID"].'"'));
                   // echo $this->db->last_query();
        		}else{
        			$exememo = $sendinfo['error_msg'];
        			$postdata["isexe"] = 2;
					
					//交运失败，保存到订单备注
					$rsdb = $this->db->get_one("SELECT order_id,email,remark FROM db_order_list WHERE order_sn='".$sendinfo['orderID']."'");
					$update_order = "";
					$update_order["remark"] = $rsdb["remark"]."  交运失败：".$exememo;
					$this->db->query($this->db->update_string('db_order_list', $update_order, 'order_id="' .$rsdb["order_id"].'"'));

        		}
        		$postdata["exememo"] = $exememo;
        		$postdata["mailinstime"] =time();
        		$this->db->query($this->db->update_string('db_mabangorder', $postdata, 'id=' .$sendinfo["id"]));
            }
            
            //echo $this->db->last_query();
        }
        //echo "<div align='center'>交运处理完成，你可以关闭当前页或停留在此页；</div>";
    }
    //打印标签信息
    public function  printrOrderLabel(){
        $id = dhtml($_GET['id']);
		if($_GET['id']<0){
			echo 'you have not select orders';
		}else{
            if(strpos($id,',') === false){
                $inid=$id;    
            }else{
                //$id = substr($id,0,-1);
                $id=trim($id,',');
                $inid = explode(",",$id);
            }
			$this->db->where_in('id', $inid);
			$this->db->order_by('id', 'DESC');
			$orderinfo = $this->db->get('db_mabangorder')->result_array();

			if(count($orderinfo)){
			     $order_sn_arr=array();
				foreach($orderinfo as $key=>$rs){
				    $rs["orderID"]=str_replace("\\r",'',trim($rs["orderID"])); 
				    $order_sn_arr[]=$rs["orderID"];
                    if(!empty($rs['mailNo'])){
                        $express_arr[]=$rs['mailNo'];
                    }
                    if($order_data['isform']==1){
                        $goodslist = $this->db->get_where('db_mabangsell',"orderid ='".$order_data["orderID"]."'")->result_array();
            			if(count($goodslist)>0){
            			     $weight=0;
            				foreach($goodslist as $sd=>$goods){
            				    $goodslist[$sd]['goods_name']= $goods['productname']; 
                                $goodslist[$sd]['goods_sn']= $goods['productid'];  
                                $goodslist[$sd]['goods_number']= $goods['ordernum'];
                                $goodslist[$sd]["stock"]=array("storage_name"=>'',
                                'positions'=>$goods['locationad'],'stock'=>$goods['stock']);
        						$orderinfo[$key]["shopname"] = $goods["shopname"];
                                
            				}
                            $orderinfo[$key]["goodslist"] = $goodslist;  
                        }

                    }else{
    					$rsOrder = $this->CI->fun->getdatabasesdetail('db_order_list'," AND order_sn='".$rs["orderID"]."'");
    					if($rsOrder){
    						$goodslist = $this->db->get_where('db_order_sell',"order_id ='".$rsOrder["order_id"]."'")->result_array();
    						foreach($goodslist as $sd =>$goods)
    						{
                               $goodinfo = $this->CI->fun->getdatabasesdetail("db_goods"," AND goods_id=".$goods['goods_id']);
                                if($goodinfo){
                                    $goodslist[$sd]['goods_name']= $goodinfo['goods_name'];   
                                }
                                if($rs['orderType']!=10){
                                    $stock_where=" AND storage_id = 1";   
                                }
    							$stock = $this->CI->fun->getdatabaseslist('db_goods_stock'," AND goods_id='".$goods["goods_id"]."' $stock_where");
    							$goodslist[$sd]["stock"] = $stock;
    						}
                            if( $rs['customerprovince']==''){
                                if(strlen($rs["orderID"])>15){
                                    $topwidth="362px";
                                }else{
                                    $topwidth="350px";
                                }    
                            }else{
                                if(strlen($rs["orderID"])>15){
                                    $topwidth="374px";
                                }else{
                                    $topwidth="362px";    
                                }
                            }
                            
                            $orderinfo[$key]["topwidth"] =$topwidth;
    						$orderinfo[$key]["shopname"] = $rsOrder["shopname"];
    						$orderinfo[$key]["shopoper"] = $rsOrder["shopoper"];
    						$orderinfo[$key]["tradeid"] = $rsOrder["tradeid"];
    						$orderinfo[$key]["remark"] = $rsOrder["remark"];
                            $orderinfo[$key]["platform_message"] = $rsOrder["platform_message"];
                            $orderinfo[$key]["userid"] = $rsOrder["customerid"];
                            $orderinfo[$key]["print_date"] =date("Y/m/d <br>H:i");
                            $orderinfo[$key]["billCode"] =substr($rs['mailNo'],0,4)."&nbsp;&nbsp;&nbsp;".substr($rs['mailNo'],4,4).
                            "&nbsp;&nbsp;&nbsp;".substr($rs['mailNo'],8,4);
                            $orderinfo[$key]['customertel1']=$rs['customertel1']=='null'?$rs['customertel2']:$rs['customertel1'];
                            $orderinfo[$key]["user_mobile"] =substr($rs['customertel1'],0,4)."****".substr($rs['customertel1'],8,4);
                            $orderinfo[$key]["address_len"] =strlen($rs['customeraddress'])>80?'height:77px;overflow:hidden':'';
    						$orderinfo[$key]["goodslist"] = $goodslist;
                            $orderinfo[$key]["packageinfo"] = explode("||",$rs['content1']);
    					}
                    }
                    $goods_total=0;
                    if(is_array($goodslist)){
                        foreach($goodslist as $g_index=>$val){
                            $goods_total+=$val['goods_number']; 
 
                             
                        }
                        $orderinfo[$key]["goods_total"] =$goods_total ;  
                    }
  
                    
                    $orderinfo[$key]["print_img"]=explode('|',$rs['print_img']);
                    $img_count=count($orderinfo[$key]["print_img"]);
                    if($rs['orderType']==4){
                        if($img_count>1){
                            unset($orderinfo[$key]["print_img"][$img_count-1]);    
                        }
                    }
                    
				}
            }
            if($orderinfo[0]['orderType']==4 && count($orderinfo)>0){
        		$user_conf_json = stripslashes($this->CI->config->item("shipment_conf_cne"));
        		$user_conf = unserialize($user_conf_json);
                $icID=$user_conf['user_id'];// //9031
                $CNEpass=$user_conf['pass'];//  //U2oxeMzdBPYk1vB
                $cNums=implode(',',$express_arr);
                $signature=md5($icID.$cNums.$CNEpass);
                $labelurl="http://label.cnexps.com/CnePrint?icID={$icID}&cNums={$cNums}&ptemp=label10x10_1&signature={$signature}";
                //echo $labelurl;
                Header("Location: $labelurl"); 
                die;
            }
            if($orderinfo[0]['orderType']==5 && count($orderinfo)>0){
                $this->sureUBIexpressOrder($order_sn_arr); 
                $info=$this->printUBIlabel2($order_sn_arr);
                if($info['site_path']){
                        Header("Location: $info[site_path]"); 
                };
                
                die;
            }
			$this->CI->tpl->assign("orderinfo",$orderinfo);
			$this->CI->tpl->display("order/printrEexpressLabel.tpl",0,0,1);//打印标签信息DHL,ubi,cne  
        }
    }  

    function build_headers($method, $path, $acceptType='application/json'){
		$walltech_date=date(DATE_RSS);
		$auth = $method."\n".$walltech_date."\n".$path;
		$hash=base64_encode(hash_hmac('sha1', $auth, $this->SECRET_KEY, true));
		//echo $walltech_date."<br>".$auth."<br>".$hash."<br>";
		return array(	'Content-Type: application/json',
						'Accept: '.$acceptType,
						'X-WallTech-Date: '.$walltech_date,
						'Authorization: WallTech '.$this->ACCESS_TOKEN.':'.$hash);
	}

    public function shipmentLog($ret){
		//日志信息
		$imgdata="";
		$imgdata["goods_id"] = $ret["order_id"];	//订单ID db_order_list
        $imgdata["updatetime"] = date("Y-m-d H:i:s");
        $imgdata["createUid"] = $_COOKIE['userid'];
        $imgdata["types"] = 3;
        $imgdata["content"] = '交运成功,订单号：'.$ret['order_sn']."&nbsp;&nbsp;运单号：".$ret["mailNo"];
        $imgdata["createUser"] =$_COOKIE['username'];
        $this->db->insert('db_goods_log', $imgdata);
        return true;
    }
	
	function requestJIACPost($posturl,$body){
	   
		$ch = curl_init($posturl);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');  
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if(strpos($posturl,"ttps")>0){
    		//禁用后curl将终止服务端进行验证
    		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
    		//检查服务器ssl证书中是否存在一个公用名
    		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);
        }
        //当需要通过curl_getinfo来获取发出请求的header信息时，该选项需要设置为true
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);   
		curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
		$response= curl_exec($ch);
        $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);//请求头
        dump($request_header);
        return $response;
	}
    
    function send_request($method,$headers,$body){
		$ch = curl_init($this->WALLTECH_SERVER.$method);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');  
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if(strpos($this->WALLTECH_SERVER,"ttps")>0){
    		//禁用后curl将终止服务端进行验证
    		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
    		//检查服务器ssl证书中是否存在一个公用名
    		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);
        }
        //当需要通过curl_getinfo来获取发出请求的header信息时，该选项需要设置为true
        //curl_setopt($ch, CURLINFO_HEADER_OUT, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);   
		curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
		$response= curl_exec($ch);
        //$request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);//请求头
        //dump($request_header);
        return $response;
	}
	

	public function printUBIlabel($order_sn_list){

		$method='/services/integration/shipper/labels';
		$headers=$this->build_headers('POST', $this->WALLTECH_SERVER.$method,'application/octet-stream');
        $order_sn_json=json_encode($order_sn_list);
		$body=$order_sn_json;
		$site_root=$_SERVER['DOCUMENT_ROOT'];
		$img_content=$this->send_request($method,$headers,$body);
        $dir = rtrim($site_root,'/'). "/uploads/ubiexpress/".date("Ymd");
        !is_dir($dir) && @mkdir($dir, 0755, true);
        $Path = $dir. "/{$order_sn_list[0]}.pdf";
		file_put_contents($Path, $img_content);//base64_decode(
        $site_path="/uploads/ubiexpress/".date("Ymd")."/{$order_sn_list[0]}.pdf";
        $imgpath=array('path_full'=>$Path,'site_path'=>$site_path);
        return $imgpath;
	}
	public function printUBIlabel2($order_sn_list){
		$method='/services/integration/shipper/labels';
		$headers=$this->build_headers('POST', $this->WALLTECH_SERVER.$method,'application/octet-stream');
        $order_sn_json=json_encode($order_sn_list);
		$body=$order_sn_json;
		$site_root=$_SERVER['DOCUMENT_ROOT'];
		$img_content=$this->send_request($method,$headers,$body);
        $dir = rtrim($site_root,'/'). "/uploads/ubiexpress/";//.date("Ymd")
        !is_dir($dir) && @mkdir($dir, 0755, true);
        $Path = $dir. "/ubilabelall.pdf";
		file_put_contents($Path, $img_content);//base64_decode(
        $site_path="/uploads/ubiexpress/ubilabelall.pdf";///uploads/ubiexpress/".date("Ymd")."/ubilabelall.pdf
        $imgpath=array('path_full'=>$Path,'site_path'=>$site_path);
        return $imgpath;
	}
	

		//保存远程数据
	public function saveRemoteData($postdata,$mabang_id)
	{
		$this->db2 = $this->CI->load->database('amazondata', TRUE);
		$row  = $this->db2->get_one("SELECT * FROM newshop_logistics.db_mabangorder where orderID = '".$postdata['orderID']."'");
		if($row['id'])
		{
			$sql="UPDATE newshop_logistics.db_mabangorder SET ";
		}else{
			$sql="INSERT INTO newshop_logistics.db_mabangorder SET ";
		}
		$sql.="isform = 0";
        $sql.=",isexe=0";
		$sql.=",statusst='".$postdata['statusst']."'";
		$sql.=",orderType='".$postdata['orderType']."'";
		$sql.=",orderID='".$postdata['orderID']."'";
		$sql.=",mabang_id='".$mabang_id."'";
		$sql.=",customerid='".$postdata['customerid']."'";
		$sql.=",customertype='".$postdata['customertype']."'";
		$sql.=",customertel1='".$postdata['customertel1']."'";
		$sql.=",customertel2='".$postdata['customertel2']."'";
		$sql.=",customerqq='".$postdata['customerqq']."'";
		$sql.=",customercountry='".$postdata['customercountry']."'";
		$sql.=",customerprovince='".$postdata['customerprovince']."'";
		$sql.=",customercity='".addslashes($postdata['customercity'])."'";
		$sql.=",customeraddress='".addslashes($postdata['customeraddress'])."'";
		$sql.=",customerzipcode='".$postdata['customerzipcode']."'";
		$sql.=",moneytype='".$postdata['moneytype']."'";
		$sql.=",content1='".$postdata['content1']."'";
		$sql.=",intime='".$postdata['intime']."'";
		$sql.=",createUser='".$postdata['createUser']."'";
		if($row['id'])
		{
			$sql.=" where id='".$row['id']."'"; 
		}
		
		$this->db2->query($sql);
	}
	//获取远程数据到本地
	public function GetOverDHLexpresslist()
	{

		$this->db2 = $this->CI->load->database('amazondata', TRUE);
		$site_root=$_SERVER['DOCUMENT_ROOT'];
		$row  = $this->db2->get_one("SELECT * FROM newshop_logistics.db_mabangorder where isform = 0 and isexe !=0 AND orderType=3 order by id asc LIMIT 0,1");
		if($row)
		{	
			 if($row['isexe']==1){//交运成功
				//保存图片到本地
				$rsdb = $this->db->get_one("SELECT order_id,email FROM db_order_list WHERE order_sn='".$row['orderID']."'");
				$dir = $site_root. "/uploads/dhlexpress/".date("Ymd");
				!is_dir($dir) && @mkdir($dir, 0755, true);
				$Path = $dir. "/".$row['orderID']."-order.pdf";
                $stie_path="/uploads/dhlexpress/".date("Ymd")."/".$row['orderID']."-order.pdf";
				$content=$row['printUrl'];
			
				file_put_contents($Path, base64_decode($content));
				$order_data["printUrl"] = $stie_path;
				$rsdbts = $this->CI->fun->pdf2png($Path,'dhlexpress');
                if(!empty($rsdbts[0])){
                    $image_urls=implode('|',$rsdbts);
                    $order_data["label_img"] = $image_urls;    
                }
				$postdata["isexe"] = 1;
				$postdata["mailNo"] = $row['mailNo'];
				$postdata["originCode"] = 0;
				$postdata["destCode"] = 0;
				$postdata['printUrl']=$order_data["printUrl"];
				$postdata["print_img"] =$order_data["label_img"];
				$postdata["mailinstime"] =time();
				$this->db->query($this->db->update_string('db_mabangorder', $postdata, 'id=' .$row["mabang_id"]));
				$this->shipmentLog(array('order_id'=>$rsdb['order_id'],"mailNo"=>$row['mailNo'],"order_sn"=>$row['orderID']));    
				
				//将货号单号、物流公司更新到订单信息
				$update_order = "";
				$update_order["shipping_number"] = $row['mailNo'];	//运单号
				$update_order["shipping_time"] = time();				//交运时间
				$update_order["shipping_name"] = 'DHL';
				$shipping =$this->CI->fun->getdatabasesdetail("db_order_express"," AND name='DHL'");
				$update_order["shipping_id"] = $shipping["id"];
				$this->db->query($this->db->update_string('db_order_list', $update_order, 'order_sn="' .$row["orderID"].'"'));
                
            }else{//交运失败
				$postdata["isexe"] = 2;
				$postdata["originCode"] = 0;
				$postdata["destCode"] = 0;
				$postdata['exememo']=$row["exememo"];
				$postdata["mailinstime"] =time();
				$this->db->query($this->db->update_string('db_mabangorder', $postdata, 'id=' .$row["mabang_id"]));

				//交运失败，保存到订单备注
				$rsdb = $this->db->get_one("SELECT order_id,email,remark FROM db_order_list WHERE order_sn='".$row['orderID']."'");
				$update_order = "";
				$update_order["remark"] = $rsdb["remark"]."  交运失败：".$row["exememo"];
				$this->db->query($this->db->update_string('db_order_list', $update_order, 'order_id="' .$rsdb["order_id"].'"'));
            }
			$this->db2->query($this->db2->update_string('newshop_logistics.db_mabangorder',array("isform"=>1), 'id=' .$row["id"]));
			return true;
				
		}else{
			return false;
		}
	
	}
}